const { Controller } = require('egg')
const svgCaptcha = require('svg-captcha')

class HomeController extends Controller {
  // 获得首页轮播图
  async getBanners() {
    const { ctx, app } = this
    // 获得轮播图数据
    const banners = await app.model.Banners.findAll()
    // 更新数据表中的访问人数 插入数据 存时间戳
    await app.model.VisitNum.create({
      visit_num: 1,
      date: new Date().getTime()
    })
    if (!banners) {
      ctx.throw(500, 'banners not found')
    }
    ctx.apiSuccess(banners)
  }
  // 查询今日数据
  async getVisitNum() {
    const { ctx, app } = this
    // 今日数据
    let todayData = await app.model.VisitNum.findAll({
      where: {
        date: {
          [app.Sequelize.Op.between]: [
            new Date(new Date().setHours(0, 0, 0, 0)),
            new Date(new Date().setHours(23, 59, 59, 999))
          ]
        }
      }
    })
    // 总数据
    let allData = await app.model.VisitNum.findAll()
    // 格式整理
    todayData = JSON.parse(JSON.stringify(todayData)).length
    allData = JSON.parse(JSON.stringify(allData)).length

    ctx.apiSuccess({
      todayData,
      allData
    })
  }
  // 获得图形验证码 admin
  async getCaptcha() {
    const { ctx } = this
    ctx.validate({
      codeKey: {
        type: 'string',
        required: false,
        desc: '验证码key'
      }
    })
    const { codeKey } = ctx.request.query
    // 移除redis中的验证码
    if (codeKey) {
      await this.service.cache.remove('code_' + codeKey)
    }
    const captcha = svgCaptcha.createMathExpr({
      size: 4, // 验证码长度
      fontSize: 50, // 字体大小
      width: 100, // 验证码宽度
      height: 40, // 验证码高度
      background: '#cc9966' // 背景颜色
    })

    // 生成一个唯一的键来存储验证码
    const key = Date.now().toString()
    // 将验证码文本存储 redis中
    const redis = await this.service.cache.set('code_' + key, captcha.text, 60 * 5)
    if (!redis) {
      ctx.apiFail('验证码生成失败')
      return
    }

    ctx.response.type = 'image/svg+xml'
    ctx.apiSuccess({
      key,
      svg: captcha.data
    })
  }

  // 新增轮播图 admin
  async addBannesr() {
    const { ctx, app, service } = this
    ctx.validate({
      title: {
        type: 'string',
        required: true,
        desc: '轮播图标题'
      },
      subtitle: {
        type: 'string',
        required: true,
        desc: '轮播图次标题'
      },
      desc: {
        type: 'string',
        required: true,
        desc: '轮播图描述'
      },
      gitee_url: {
        type: 'string',
        required: true,
        desc: 'gitee地址'
      }
    })
    const { title, subtitle, desc, gitee_url } = ctx.request.body
    // 上传文件
    const file = ctx.request.files[0]
    let Location = ''
    try {
      Location = await service.upload.upload(file)
    } catch {
      return ctx.apiFail('文件上传失败')
    }

    console.log(Location, '---------------')
    // 插入数据库
    const resolve = await app.model.Banners.create({
      title,
      subtitle,
      desc,
      gitee_url,
      poster: `http://${Location.Location}`
    })
    if (!resolve) return ctx.apiFail('轮播图新增失败')
    ctx.apiSuccess(resolve)
  }

  // 删除轮播图 admin
  async deleteBanner() {
    const { ctx, app } = this
    ctx.validate({
      id: {
        type: 'string',
        required: true,
        desc: '轮播图id'
      }
    })
    const { id } = ctx.request.query
    // 删除数据库中的数据
    const resolve = await app.model.Banners.findByPk(id)
    if (!resolve) return ctx.apiFail('轮播图不存在')
    const deleteResolve = await resolve.destroy()
    if (!deleteResolve) return ctx.apiFail('轮播图删除失败')
    ctx.apiSuccess(deleteResolve)
  }

  // 编辑轮播图 admin
  async editBanner() {
    const { ctx, app, service } = this
    ctx.validate({
      id: {
        type: 'string',
        required: true,
        desc: '轮播图id'
      },
      title: {
        type: 'string',
        required: true,
        desc: '轮播图标题'
      },
      subtitle: {
        type: 'string',
        required: true,
        desc: '轮播图次标题'
      },
      desc: {
        type: 'string',
        required: true,
        desc: '轮播图描述'
      },
      gitee_url: {
        type: 'string',
        required: true,
        desc: 'gitee地址'
      },
      poster: {
        type: 'string',
        required: false,
        desc: '轮播图地址'
      }
    })
    const { id, title, subtitle, desc, gitee_url, poster } = ctx.request.body
    // 上传文件
    let Location = ''
    if (!poster) {
      const file = ctx.request.files[0]
      try {
        Location = await service.upload.upload(file)
      } catch {
        return ctx.apiFail('文件上传失败')
      }
    }
    // 更新数据库中的数据
    const resolve = await app.model.Banners.update(
      {
        title,
        subtitle,
        desc,
        gitee_url,
        poster: poster ? poster : `http://${Location.Location}`
      },
      {
        where: {
          id
        }
      }
    )
    if (!resolve) return ctx.apiFail('轮播图更新失败')
    ctx.apiSuccess(resolve)
  }

  // 管理员登录 admin
  async login() {
    const { ctx } = this
    ctx.validate({
      username: {
        type: 'string',
        required: true,
        desc: '用户名'
      },
      password: {
        type: 'string',
        required: true,
        desc: '密码'
      },
      key: {
        type: 'string',
        required: true,
        desc: '验证码key'
      },
      captcha: {
        type: 'string',
        required: true,
        desc: '验证码'
      }
    })
    const { username, password, key, captcha } = ctx.request.body
    // 匹配captcha
    const redis = await this.service.cache.get('code_' + key)
    if (!redis) {
      ctx.apiFail('验证码已过期')
      return
    }
    if (redis !== captcha) {
      ctx.apiFail('验证码错误')
      return
    }
    // 查询用户
    let user = await ctx.model.AdminUser.findOne({
      where: {
        username,
        password
      }
    })
    if (!user) {
      ctx.apiFail('用户名或密码错误')
      return
    }
    // 生成token
    user = JSON.parse(JSON.stringify(user))
    const token = await ctx.getToken(user)
    user.token = token
    // 存储token
    const redisToken = await this.service.cache.set('token_' + user.id, token)
    if (!redisToken) return ctx.apiFail('token储存失败')
    // 删除redis中的key
    const deleteKey = await this.service.cache.remove('code_' + key)
    if (!deleteKey) {
      ctx.apiFail('验证码删除失败')
      return
    }
    ctx.apiSuccess(user)
  }
  // 退出登录 admin
  async exitLogin() {
    // 用户退出
    const { ctx, service } = this
    // 1. 获得用户的id
    const { id } = ctx.authUser
    // 2. 删除缓存中的token
    const cacheToken = await service.cache.remove('token_' + id)
    if (cacheToken) {
      ctx.apiSuccess('退出成功')
    } else {
      ctx.apiFail('退出失败')
    }
  }
}

module.exports = HomeController
